#ParallelPlatform Project - A web platform to distribute and share knowledge
#Copyright (C) 2011  Daniel Guerrero Martinez & Sergio Rodriguez Lumley
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
from django.contrib.auth.decorators import login_required, permission_required

from form import ResourceForm

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
@login_required
@permission_required('permissions_wiki.can_add_resources')
def upload(request):
    
    if request.method == 'POST':
        form = ResourceForm(request.POST, request.FILES)
        if form.is_valid():
            file = form.save();
            if "lastupload" in request.session:
                del request.session['lastupload']
            if 'lastupload' in request.POST and request.POST['lastupload']:
                request.session['lastupload'] = file.file.url
            return json_response({ 'success' : True, 'url' : file.file.url })
    
    return json_response({ 'success' : False, 'error' : 'The resource is null or not valid' })

@csrf_exempt
@login_required
@permission_required('permissions_wiki.can_add_resources')
def lastUpload(request):
    
    if "lastupload" in request.session:
        lastSave = request.session['lastupload']
        del request.session['lastupload']
        return json_response({ 'success' : True, 'lastupload' : lastSave })
    else:
        return json_response({ 'success' : False })
    
    
def json_response(data):
    import json
    from django.http import HttpResponse
    return HttpResponse(json.dumps(data, sort_keys=True),
                        content_type='text/plain')








 
